package com.momoauth.common.tps.qiniu.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
public class QiniuUploadUtil {

    /**
     * 文件上传
     * @param file
     * @param domain
     * @param accessKey
     * @param secretKey
     * @param bucket
     * @return
     * @throws IOException
     */
    public static String upload(
            MultipartFile file,
            String domain,
            String accessKey,
            String secretKey,
            String bucket
    ) throws IOException {
        Configuration configuration = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(configuration);
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(bucket);

        // 这里使用UUID作为文件名称
        String fileName = UUID.randomUUID() + "." + getFileSuffix(file.getOriginalFilename());

        try {
            Response response = uploadManager.put(file.getBytes(), fileName, uploadToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return domain + "/" + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
        }
        return null;
    }

    /**
     * 文件后缀名
     * @param fileName
     * @return
     */
    public static String getFileSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
